package com.zou.music_downloader.secondaryfragments;

import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.zou.music_downloader.R;
import com.zou.music_downloader.adapter.SugestionAdapter;
import com.zou.music_downloader.bean.SearchSugestionBean;
import com.zou.music_downloader.bean.SimpleSearchSugestionEntity;
import com.zou.music_downloader.utils.BMA;
import com.zou.music_downloader.utils.HandleSugestionBean;
import com.zou.music_downloader.utils.VolleyUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zou on 2016/3/12.
 */
@EFragment(R.layout.sfragment_result)
public class ResultFragment extends Fragment {
    @ViewById(R.id.result_errorview)
    LinearLayout error;

    @ViewById(R.id.rcv_result)
    RecyclerView rcv;

    List<SimpleSearchSugestionEntity> datas = new ArrayList<>();
    private Gson             gson;
    private SugestionAdapter adapter;


    @AfterViews
    void afterView() {
        rcv.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new SugestionAdapter(getContext(), datas, getFragmentManager());
        rcv.setAdapter(adapter);
    }

    public void setData(String queryText) {
        RequestQueue requestQueue = VolleyUtil.getQueue(getContext());
        StringRequest stringRequest = new StringRequest(BMA.Search.searchSugestion(queryText)
                , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("wocao", "onResponse: " + response);
                gson = new Gson();
                datas.clear();
                datas.addAll(HandleSugestionBean.castToResultEntity(gson.fromJson(response, SearchSugestionBean.class)));
                if (datas.size() == 0) {
                    error.setVisibility(View.VISIBLE);
                } else {
                    error.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();

            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(stringRequest);
    }
}
